Skip to main content

dxapi

InstrumentMessage​

class InstrumentMessage(object)

setTimestamp​

def setTimestamp(timestamp: int)

Set timestamp for message.

Arguments:

  • timestamp - int, epoch time in millis.

setDateTime​

def setDateTime(timestamp: datetime)

Set timestamp for message from datetime.

Arguments:

  • timestamp - datetime object.

getDateTime​

def getDateTime()

Returns timestamp of message as datetime object.

setNanoTime​

def setNanoTime(timestamp: int)

Set timestamp for message.

Arguments:

  • timestamp - int, epoch time in nanos.

getNanoTime​

def getNanoTime()

Returns timestamp of message (epoch time in nanos).

to_dict​

def to_dict(attributes: list[str] = None) -> dict

Convert object attributes to a dictionary.

Arguments:

  • attributes list[str], optional - List of attribute names to include in the dictionary. If None, all public attributes are included.

CompactMessage​

class CompactMessage(InstrumentMessage)

Base class of messages returned by a cursor opened with SelectionOptions.compactMessages = True.

It is an InstrumentMessage, but the fields are stored in slots instead of dict: every message type gets its own subclass with slots generated from the stream schema. Reading messages is faster and uses less memory.

Differences from a regular InstrumentMessage:

  • vars(msg) and msg.dict do NOT contain the fields (the dictionary is empty), use msg.to_dict() instead;
  • field names that are not valid Python identifiers have every invalid character replaced with '' ('E.exchangeId' -> 'E_exchangeId'); a leading digit gets an 'f' prefix ('1abc' -> 'f_1abc'); if converted names of two fields coincide, '_' is appended to the second;
  • a field whose name cannot be a slot gets the 'f_' prefix as well: names starting with '__' ('_x' -> 'f___x', Python would mangle it) and names of attributes of the message class itself ('to_dict' -> 'f_to_dict', 'fields' -> 'f__fields', 'class' -> 'f___class', ...);
  • the messages can be sent with TickLoader.send(): the fields are read from the slots and matched with the fields of the stream schema (also those whose names were converted);
  • the messages cannot be pickled (the generated classes are not importable by name), so they cannot be passed between processes (multiprocessing); use to_dict() or copy.deepcopy() (deepcopy works);
  • the option is applied by cursors only: pandas reading (DataFrame functions) ignores it.

to_dict​

def to_dict(attributes: list[str] = None) -> dict

Convert object attributes to a dictionary.

Arguments:

  • attributes list[str], optional - List of attribute names to include in the dictionary. If None, all public attributes are included.

InstrumentType​

class InstrumentType(object)

Represents instrument type.

Object of this class can be created from instrument type name (str), or int value:

Example:

fxType = dxapi.InstrumentType('FX')
indexType = dxapi.InstrumentType(dxapi.InstrumentType.INDEX)

Possible values:

EQUITY
OPTION
FUTURE
BOND
FX
INDEX
ETF
CUSTOM
SIMPLE_OPTION
EXCHANGE
TRADING_SESSION
STREAM
DATA_CONNECTOR
EXCHANGE_TRADED_SYNTHETIC
SYSTEM
CFD
UNKNOWN

InstrumentIdentity​

class InstrumentIdentity(object)

Represents instrument, contains from instrument type and instrument symbol.

Example:

appleId = dxapi.InstrumentIdentity(dxapi.InstrumentType('EQUITY'), 'AAPL')
btcUsdId = dxapi.InstrumentIdentity(dxapi.InstrumentType.FX, 'BTC/USD')

StreamScope​

class StreamScope(object)

Determines the scope of a stream's durability, if any.

Example:

scope = dxapi.StreamScope('TRANSIENT')

Possible values:

DURABLE,
EXTERNAL_FILE,
TRANSIENT,
RUNTIME

WriteMode​

class WriteMode(object)

APPEND: Adds only new data into a stream without truncations. REPLACE: Adds data into a stream and removes previous data older that first message time [truncate(first message time + 1)]. REWRITE: Default. Adds data into a stream and removes previous data by truncating using first message time. [truncate(first message time)]. TRUNCATE: Stream truncated every time when loader writes a messages earlier than last message time. INSERT: New data inserts into a stream without truncations.

Example:

mode = dxapi.WriteMode('TRUNCATE')

Possible values:

APPEND,
REPLACE,
REWRITE,
TRUNCATE,
INSERT

DecimalType​

class DecimalType(enum.Enum)

Specifies output type for decimal fields.

Possible values:

DOUBLE,
DECIMAL

SelectionOptions​

class SelectionOptions(object)

Options for selecting data from a stream.

Example:

so = dxapi.SelectionOptions()
so._from = 0
so.to = 100000
so.useCompression = False
so.live = True
so.reverse = False
so.allowLateOutOfOrder = True
so.realTimeNotification = True
so.minLatency = False

Properties:

  • _from int - Start timestamp in millis.

  • to int - End timestamp in millis.

  • useCompression bool - Compress the data sent by the server (gzip). None (default) means the value set by TickDb.setCompression() is used.

  • live bool - Instead of returning false from next () at the end of the stream, wait for live data to be added.

  • reverse bool - Specify cursor direction.

  • autoClose bool - Specifies whether the cursor should be automatically closed on reaching end of stream in non-live mode. Has no effect in live mode, cursor needs to be closed manually.

  • allowLateOutOfOrder bool - Output out-of-order late messages. Timebase consumers receive historical messages they requested strictly ordered by their time. For scenarios when new messages arrive in the middle of consumer's session (So called 'live' mode) it is possible that newly arrived message has a timestamp in already consumer time region. In this cases this flag allows consumer to receive these 'late' messages even if they out of order with respect to current baseline time.

  • NOTE - Late Messages that are timestamped prior to consumer's select time or last reset time will not be delivered even with this flag enabled.

  • rebroadcast bool - Allow rebroadcast unique message on open/reset cursors.

  • realTimeNotification bool - Enabled/Disables sending system messages when cursor switches from historical to realtime mode.

  • minLatency bool - try to receive messages ASAP, with minimal buffering. Can potentially reduce max throughput and increase CPU use / network bandwidth usage.

  • decimalType DecimalType enum - specifies output type for decimal fields.

  • compactMessages bool - if True, a cursor returns CompactMessage objects (based on slots, faster to read and smaller) instead of InstrumentMessage objects. Default is False. CompactMessage is a subclass of InstrumentMessage, but vars()/dict do not contain the fields (use to_dict()). Field names that are not valid Python identifiers are converted ('E.exchangeId' -> 'E_exchangeId'), see CompactMessage for the rules. Compact messages can be sent to a loader, but cannot be pickled. The option is ignored by pandas (DataFrame) reading.

withSpaces​

def withSpaces(spaces: 'list[str]') -> None

List of spaces to select data from. If set to None then data from all spaces is loaded.

LoadingOptions​

class LoadingOptions(object)

Options for loading data into a stream.

Example:

lo = dxapi.LoadingOptions()
lo.writeMode = dxapi.WriteMode('TRUNCATE')
lo.space = 'myspace'
lo.minLatency = False

Properties:

  • writeMode WriteMode - see WriteMode class description.

  • minLatency bool - try to send messages ASAP, with minimal buffering. Can potentially reduce max throughput and increase CPU use / network bandwidth usage.

  • useCompression bool - compress the data sent to the server (gzip). Reduces network traffic, increases CPU use. None (default) means the value set by TickDb.setCompression() is used.

  • space str - Data Partition. Contains unique number of instruments or Time Ranges.

StreamOptions​

class StreamOptions(object)

Stream definition attributes.

Example:

so = dxapi.StreamOptions()
so.name('Test Name')
so.description('Test Description')
so.owner('Test Owner')
so.metadata(schema)
so.scope = dxapi.StreamScope('TRANSIENT')
so.distributionFactor = 1
so.polymorphic = True
so.periodicity = 'STATIC'
so.unique = True
so.duplicatesAllowed = False
so.version = '4.3'

db.createStream(key, so)

Properties:

  • scope StreamScope - Determines persistent properties of a stream.

  • distributionFactor int - The number of M-files into which to distribute the data. Supply MAX_DISTRIBUTION to keep a separate file for each instrument (default).

  • duplicatesAllowed bool - Indicates that loader will ignore binary similar messages(for 'unique' streams only).

  • highAvailability bool - High availability durable streams are cached on startup.

  • unique bool - Unique streams maintain in-memory cache of resent messages. This concept assumes that stream messages will have some field(s) marked as primary key. Primary key may be a simple field (e.g. symbol) or composite (e.g. symbol and portfolio ID). For each key TimeBase runtime maintains a copy of the last message received for this key (cache). Each new consumer will receive a snapshot of current cache at the beginning of live data subscription.

    polymorphic (bool).

  • periodicity bool - Stream periodicity, if known.

  • version str - Stream format version. Supported versions are: '5.0' - Editable past format, TS data file; '4.3' - 'Classic' storage format, allocation free.

name​

def name(name: str = None) -> str

Optional user-readable name.

description​

def description(description: str = None) -> str

Optional multi-line description.

owner​

def owner(owner: str = None) -> str

Optional owner of stream. During stream creation it will be set equals to authenticated user name.

location​

def location(location: str = None) -> str

Location of the stream (by default null). When defined this attribute provides alternative stream location (rather than default location under QuantServerHome)

distributionRuleName​

def distributionRuleName(distributionRuleName: str = None) -> str

Class name of the distribution rule

metadata​

def metadata(metadata: SchemaDef | str | None = None) -> SchemaDef

Stream metadata (SchemaDef or json string) as dxapi.SchemaDef object.

schema​

def schema(metadata: 'SchemaDef | str' = None) -> 'SchemaDef'

Stream metadata (SchemaDef or json string) as dxapi.SchemaDef object. Alias for metadata().

metadataXml​

def metadataXml(metadataXml: str = None) -> str

Stream metadata in XML format.

QueryParameter​

class QueryParameter(object)

Input parameter definition for a prepared statement.

QueryToken​

class QueryToken(object)

Lexical token from TickDb.compileQuery (server lexer output).

Properties: type (str): token kind name (KEYWORD, IDENTIFIER, ...). location (int): packed Location --- bits 48-63 start line, 32-47 start column, 16-31 end line, 0-15 end column (16-bit fields; 65535 means unused within a field). Decode like server Location getters.

LockType​

class LockType(object)

Represents lock type.

Object of this class can be created from instrument type name (str), or int value:

Example:

readLockType = dxapi.LockType('READ')
writeLockType = dxapi.LockType('WRITE')
writeLockType = dxapi.LockType(dxapi.LockType.READ_LOCK)

Possible values:

READ,
WRITE

LockOptions​

class LockOptions(object)

Options for stream locking.

Example:

lo = dxapi.LockOptions()
lo.type = dxapi.LockType('WRITE')
lo.startTime = 0
lo.endTime = 1000

Properties:

  • type LockType - type of lock;

  • startTime int - Start time for ranged write locks (ms);

  • endTime int - End time for ranged write locks (ms).

ExecutionStatus​

class ExecutionStatus(object)

Background process status.

Object of this class can be created from instrument type name (str), or int value:

Possible values:

NONE,
RUNNING,
COMPLETED,
ABORTED,
FAILED

BackgroundProcessInfo​

class BackgroundProcessInfo(object)

Background process info.

Example:

stream.changeSchema(schema, None, defaults, True)
while str(stream.backgroundProcessInfo().status) != 'Completed':
print('Waiting task to finish...')
time.sleep(1)

Properties:

  • status ExecutionStatus - status of process;

  • progress double - progress of process (from 0.0 to 1.0);

  • startTime int - task start time in millis;

  • endTime int - task start time in millis.

TickDb​

class TickDb(object)

The top-level implementation to the methods of the Deltix Tick Database engine. Instances of this class are created by static method createFromUrl:

db = dxapi.TickDb.createFromUrl('dxtick://localhost:8011')

or

db = dxapi.TickDb.createFromUrl('dxtick://localhost:8011', 'user', 'password')

createFromUrl​

@staticmethod
def createFromUrl(url: str,
user: str = None,
password: str = None,
*,
oauth2=None,
application_name: str = None) -> "TickDb"

Creates a new database instance with the specified root folder, or URL.

Authentication mode is selected by the supplied arguments:

  • createFromUrl(url) -- anonymous connection.
  • createFromUrl(url, user, password) -- Basic auth with the given username and password.
  • createFromUrl(url, oauth2=oauth2_provider) -- OAuth2 client_credentials. The access token is obtained from the provider and used as the Basic-auth password; the Basic-auth username defaults to provider.client_id and can be overridden via user=.

With oauth2 set, the provider is stored on the instance and every subsequent server-bound call (listStreams, executeQuery, etc.) transparently refreshes the token when it is about to expire.

Arguments:

  • url str - Connection URL.

  • user str, optional - Basic-auth username. When oauth2 is given, defaults to the provider's client_id if available.

  • password str, optional - Basic-auth password. Mutually exclusive with oauth2.

  • oauth2 optional, keyword-only - Either an :class:OAuth2ClientCredentialsConfig (a new provider is created internally) or any pre-built :class:OAuth2AccessTokenProvider instance.

  • application_name str, optional, keyword-only - Custom application name set on the connection via :meth:setApplicationName before it is returned.

Returns:

  • TickDb - An un-opened TickDB instance.

Raises:

  • ValueError - oauth2 is set together with password, or user cannot be inferred from an opaque provider.

openFromUrl​

@staticmethod
@contextmanager
def openFromUrl(url: str,
readonly: bool,
user: str = None,
password: str = None,
*,
oauth2=None,
application_name: str = None)

Creates a new database instance with the specified root folder, or URL, and opens it.

Supports the same authentication modes as :meth:createFromUrl (anonymous, Basic, OAuth2 client_credentials). Equivalent to :meth:createFromUrl followed by :meth:open, wrapped in a context manager that guarantees :meth:close on exit.

Arguments:

  • url str - Connection URL.

  • readonly bool - Open data store in read-only mode.

  • user str, optional - Basic-auth username. When oauth2 is given, defaults to the provider's client_id.

  • password str, optional - Basic-auth password. Mutually exclusive with oauth2.

  • oauth2 optional, keyword-only - Either an :class:OAuth2ClientCredentialsConfig or any pre-built :class:OAuth2AccessTokenProvider.

  • application_name str, optional, keyword-only - Custom application name.

Yields:

  • TickDb - An open TickDB instance.

Raises:

  • ValueError - oauth2 is set together with password, or user cannot be inferred from an opaque provider.

setApplicationName​

def setApplicationName(name: str) -> None

Set custom visible name of application.

Arguments:

  • name str - Application name.

setCompression​

def setCompression(compression: bool) -> None

Enable compression (gzip) of the data exchanged with the server. Reduces traffic on slow networks, costs some CPU. Disabled by default. Must be called before open().

Applies to the session connection (stream list, stream properties, change notifications) and is the default for cursors and loaders: SelectionOptions.useCompression and LoadingOptions.useCompression override it if they are set (not None).

Arguments:

  • compression bool - True to enable compression.

getCompression​

def getCompression() -> bool

Returns the compression flag set by :meth:setCompression.

setAccessToken​

def setAccessToken(token: str) -> None

Set or override access token used as password for authentication.

Arguments:

  • token str - Access token.

isReadOnly​

def isReadOnly() -> bool

Determines whether the store is open as read-only.

isOpen​

def isOpen() -> bool

Determines whether the store is open.

open​

def open(readOnlyMode: bool) -> bool

Open the data store.

Arguments:

  • readOnlyMode bool - Open data store in read-only mode.

close​

def close() -> None

Closes data store.

format​

def format() -> bool

Create a new object on disk and format internally. The data store is left open for read-write at the end of this method.

generateSchema​

def generateSchema(types: list[str]) -> str

Generates SchemaDef object from specified content types.

schema = db.generateSchema(['deltix.timebase.api.messages.TradeMessage',
'deltix.timebase.api.messages.BestBidOfferMessage'])

listStreams​

def listStreams() -> list[TickStream]

Enumerates existing streams.

Returns:

  • list[TickStream] - An array of existing stream objects.

getStream​

def getStream(key: str) -> TickStream

Looks up an existing stream by key.

Arguments:

  • key str - Identifies the stream.

Returns:

  • TickStream - A stream object, or None if the key was not found.

createStream​

def createStream(key: str, options: StreamOptions) -> TickStream

Creates a new stream within the database.

Arguments:

  • key str - A required key later used to identify the stream.

  • options StreamOptions - Options for creating the stream.

Returns:

  • TickStream - A new instance of TickStream.

createFileStream​

def createFileStream(key: str, dataFile: str) -> TickStream

Creates a new stream mount to the given data file.

Arguments:

  • key str - A required key later used to identify the stream.

  • dataFile str - Path to the data file (on server side).

Returns:

  • TickStream - A new instance of TickStream.

createCursor​

def createCursor(stream: TickStream, options: SelectionOptions) -> TickCursor

Opens an initially empty cursor for reading data from multiple streams, according to the specified options. The messages are returned from the cursor strictly ordered by time. Within the same exact timestamp, the order of messages is undefined and may vary from call to call, i.e. it is non-deterministic.

The cursor is returned initially empty and must be reset. The TickCursor class provides methods for dynamically re-configuring the subscription, or jumping to a different timestamp.

Arguments:

  • stream TickStream - Stream from which data will be selected.

  • options SelectionOptions - Selection options.

Returns:

  • TickCursor - A cursor used to read messages.

tryCursor​

@contextmanager
def tryCursor(stream: TickStream, options: SelectionOptions) -> TickCursor

contextmanager version of createCursor. Usage:

with db.tryCursor(stream, options) as cursor:
while cursor.next():
message = cursor.getMessage()

select​

def select(
timestamp: int,
streams: list[TickStream],
options: SelectionOptions,
*args,
types: list[str] | None = None,
entities: list[InstrumentIdentity] | list[str] | None = None
) -> TickCursor

Opens a cursor for reading data from multiple streams, according to the specified options. The messages are returned from the cursor strictly ordered by time. Within the same exact time stamp, the order of messages is undefined and may vary from call to call, i.e. it is non-deterministic.

Note that the arguments of this method only determine the initial configuration of the cursor. The TickCursor clsas provides methods for dynamically re-configuring the subscription, or jumping to a different timestamp.

Arguments:

  • timestamp int - The start timestamp in millis.

  • streams list[TickStream] - Streams from which data will be selected.

  • options SelectionOptions - Selection options.

  • types list[str], optional - Specified message types to be subscribed. If None, all message types will be subscribed.

  • entities list[InstrumentIdentity] | list[str], optional - Specified entities/symbols to be subscribed. If None, all entities will be subscribed. Legacy positional filters are still supported as (types, entities).

Returns:

  • TickCursor - A cursor used to read messages.

trySelect​

@contextmanager
def trySelect(
timestamp: int,
streams: list[TickStream],
options: SelectionOptions,
*args,
types: list[str] | None = None,
entities: list[InstrumentIdentity] | list[str] | None = None
) -> TickCursor

Context manager version of select. Usage:

with db.trySelect(timestamp, streams, options, types, entities) as cursor:
while cursor.next():
message = cursor.getMessage()

or keyword style:

with db.trySelect(timestamp, streams, options, types=['Trade'], entities=['AAPL']) as cursor:
while cursor.next():
message = cursor.getMessage()

createLoader​

def createLoader(stream: TickStream, options: LoadingOptions) -> TickLoader

Creates a channel for loading data. The loader must be closed when the loading process is finished.

Arguments:

  • stream TickStream - stream for loading data.

  • options LoadingOptions - Loading Options.

Returns:

  • TickLoader - created loader.

tryLoader​

@contextmanager
def tryLoader(stream: TickStream, options: LoadingOptions) -> TickLoader

Contextmanager version of createLoader. Usage:

with db.tryLoader(stream, options) as loader: loader.send(message)

executeQuery​

def executeQuery(query: str,
options: SelectionOptions = None,
timestamp: int = JAVA_LONG_MIN_VALUE,
entities: list[InstrumentIdentity] | list[str] | None = None,
params: list[QueryParameter] | None = None) -> TickCursor

Execute Query and creates a message source for reading data from it, according to the specified options. The messages are returned from the cursor strictly ordered by time. Within the same exact time stamp, the order of messages is undefined and may vary from call to call, i.e. it is non-deterministic.

Arguments:

  • query str - Query text element.

  • options SelectionOptions - Selection options.

  • timestamp int - The start timestamp in millis.

  • entities list[InstrumentIdentity] - Specified entities to be subscribed. If null, then all entities will be subscribed.

  • params list[QueryParameter] - The parameter values of the query.

Returns:

  • TickCursor - An iterable message source to read messages.

tryExecuteQuery​

@contextmanager
def tryExecuteQuery(query: str,
options: SelectionOptions = None,
timestamp: int = JAVA_LONG_MIN_VALUE,
entities: list[InstrumentIdentity] | list[str]
| None = None,
params: list[QueryParameter] | None = None) -> TickCursor

Contextmanager version of executeQuery. Usage:

with db.tryExecuteQuery('select * from stream') as cursor:
while cursor.next():
message = cursor.getMessage()

compileQuery​

def compileQuery(query: str) -> list[QueryToken]

Runs server-side QQL validation/compilation and returns lexer tokens.

On success returns a list of QueryToken (may be empty).

On syntax error raises Exception with errorText and a human-readable `[at …]` range.

Arguments:

  • query str - QQL source text.

Returns:

  • list[QueryToken] - Lexical tokens from the server.

createMultiplexedCursor​

def createMultiplexedCursor(subscription: MultiplexerSubscription,
timestamp: int = None,
options: SelectionOptions = None) -> TickCursor

Creates and returns a multiplexed TickCursor for the given subscription.

Arguments:

  • subscription: MultiplexerSubscription object defining feeds
  • timestamp: Epoch time in milliseconds for the subscription (default: JAVA_LONG_MIN_VALUE)
  • options: SelectionOptions object for cursor configuration (default is an empty options object)

Raises:

  • ValueError: If subscription is None or contains no feeds
  • TypeError: If subscription is not a MultiplexerSubscription object

Returns:

TickCursor object for reading multiplexed cursor

tryMultiplexedCursor​

@contextmanager
def tryMultiplexedCursor(subscription: MultiplexerSubscription,
timestamp: int = None,
options: SelectionOptions = None) -> TickCursor

Contextmanager version of createMultiplexedCursor. Usage:

with db.tryMultiplexedCursor(subscription) as cursor:
while cursor.next():
message = cursor.getMessage()

TickStream​

class TickStream(object)

The stream is a time series of messages for a number of financial instruments ('entities'). Messages can be price bars, trade ticks, bid/offer ticks, or any of the many more built-in and user-defined types. In the simplest case, a database will have a single stream of data. Multiple streams can be used to represent data of different frequencies, or completely different factors. For instance, separate streams can represent 1-minute price bars and ticks for the same set of entities. Or, you can have price bars and volatility bars in separate streams.

Get stream:

stream = tickdb.getStream('stream_key')

List stream:

streams = tickdb.listStreams()

key​

def key() -> str

Returns the key, which uniquely identifies the stream within its database.

name​

def name() -> str

Returns a user-readable short name.

distributionFactor​

def distributionFactor() -> int

Returns the target number of files to be used for storing data.

description​

def description() -> str

Returns a user-readable multi-line description.

owner​

def owner() -> str

Returns stream owner.

location​

def location() -> str

Returns stream location.

metadata​

def metadata() -> str

Returns stream schema as dxapi.SchemaDef object.

schema​

def schema() -> str

Returns stream schema as dxapi.SchemaDef object. (Alias for metadata)

metadataXml​

def metadataXml() -> str

Returns stream schema (in xml format).

scope​

def scope() -> StreamScope

Returns stream schema (in xml format).

version​

def version() -> str

Returns stream data format version.

highAvailability​

def highAvailability() -> bool

Returns stream memory caching parameter. High availability durable streams are cached on startup.

unique​

def unique() -> bool

Unique streams maintain in-memory cache of resent messages. This concept assumes that stream messages will have some field(s) marked as primary key. Primary key may be a simple field (e.g. symbol) or composite (e.g. symbol and portfolio ID). For each key TimeBase runtime maintains a copy of the last message received for this key (cache). Each new consumer will receive a snapshot of current cache at the beginning of live data subscription.

polymorphic​

def polymorphic() -> bool

Returns whether the stream is configured as polymorphic.

periodicity​

def periodicity() -> str

Returns Stream periodicity, if known.

options​

def options() -> StreamOptions

Returns stream options object.

describe​

def describe() -> str

Returns stream DDL description.

changeSchema​

def changeSchema(schema: SchemaDef | str,
mappings: dict = None,
defaults: dict = None,
background: bool = False) -> bool

Run schema change task for stream.

Arguments:

schema (SchemaDef or str(json)): New stream schema;

  • mappings dict - column mappings in format 'TypeName:FiledName':

  • defaults dict - default values for not nullable columns.

  • background bool - true to run task in background mode, in this case method returns right after rest query to server. You can track status of background task with backgroundProcessInfo() method. You can abort task with abortBackgroundProcess() method.

backgroundProcessInfo​

def backgroundProcessInfo() -> BackgroundProcessInfo

Gets stream background process information.

abortBackgroundProcess​

def abortBackgroundProcess() -> bool

Aborts active background process if any exists

listEntities​

def listEntities(
instrumentTypes: list[InstrumentType] | None = None
) -> list[InstrumentIdentity]

Return list of instruments in stream.

Arguments:

  • instrumentTypes list[InstrumentType] - instrument types for which entities should be selected. If None, all entities of stream will be selected.

Returns:

  • list[InstrumentIdentity] - stream instruments.

listSymbols​

def listSymbols(
instrumentTypes: list[InstrumentType] | None = None) -> list[str]

Return list of symbols in stream.

Arguments:

  • instrumentTypes list[str] - instrument types for which entities should be selected. If None, all entities of stream will be selected.

Returns:

  • list[InstrumentIdentity] - stream symbols.

truncate​

def truncate(
timestamp: int,
entities: list[InstrumentIdentity] | list[str] | None = None) -> bool

Truncates stream data for the given entities from given time

Arguments:

  • timestamp int - Timestamp in millis. If time less than stream start time, then all stream data will be deleted.

  • entities list[InstrumentIdentity] - A list of entities. If None, all stream entities will be used.

Returns:

  • bool - true, if stream was truncated successfully.

clear​

def clear(
entities: list[InstrumentIdentity] | list[str] | None = None) -> bool

Clear stream data for the given entities.

Arguments:

  • entities list[InstrumentIdentity] - A list of entities. If None, all stream entities will be used.

purge​

def purge(timestamp: int) -> bool

Deletes stream data that is older than a specified time

Arguments:

timestamp (int):Purge time in milliseconds.

Returns:

  • bool - true, if stream was purged successfully.

deleteData​

def deleteData(
fromMs: int,
toMs: int,
entities: list[InstrumentIdentity] | list[str] | None = None) -> bool

Deletes stream data for the given entities using specified time range.

Arguments:

  • from int - start timestamp (inclusive). Time is measured in milliseconds that passed since January 1, 1970 UTC.

  • to int - end timestamp (inclusive). Time is measured in milliseconds that passed since January 1, 1970 UTC. If time more than stream end time, then all stream data will be deleted for the given stream.

  • entities list[InstrumentIdentity] or list[str] - A list of entities. If None, all stream entities will be used.

Returns:

  • bool - true, if stream was truncated successfully.

deleteStream​

def deleteStream() -> bool

Deletes this stream

Returns:

  • bool - true, if stream was deleted successfully.

lock​

def lock(options: LockType | LockOptions | None = None) -> None

Acquire a lock of this stream. Default lock type is WRITE.

tryLock​

def tryLock(options: LockType | LockOptions, timeout: int) -> None

Blocking operation that attempts to obtain given type of lock on this stream. If lock cannot be obtained during specified timeout operation fails with exception.

unlock​

def unlock() -> None

Releases stream lock.

select​

def select(
timestamp: int,
options: SelectionOptions,
*args,
types: list[str] | None = None,
entities: list[InstrumentIdentity] | list[str] | None = None
) -> TickCursor

Opens a cursor for reading data from this stream, according to the specified options. The messages are returned from the cursor strictly ordered by time. Within the same exact time stamp, the order of messages is undefined and may vary from call to call, i.e. it is non-deterministic.

Note that the arguments of this method only determine the initial configuration of the cursor. The TickCursor interface provides methods for dynamically re-configuring the subscription, or jumping to a different timestamp.

Arguments:

  • timestamp int - The start timestamp in millis.

  • options SelectionOptions - Selection options.

  • types list[str], optional - Specified message types to be subscribed. If None, all message types will be subscribed.

  • entities list[InstrumentIdentity] | list[str], optional - Specified entities/symbols to be subscribed. If None, all entities will be subscribed. Legacy positional filters are still supported as (types, entities).

Returns:

  • TickCursor - A cursor used to read messages.

trySelect​

@contextmanager
def trySelect(
timestamp: int,
options: SelectionOptions,
*args,
types: list[str] | None = None,
entities: list[InstrumentIdentity] | list[str] | None = None
) -> TickCursor

Contextmanager version of select. Usage:

with stream.trySelect(timestamp, options, types, entities) as cursor:
while cursor.next():
message = cursor.getMessage()

or keyword style:

with stream.trySelect(timestamp, options, types=['Trade'], entities=['AAPL']) as cursor:
while cursor.next():
message = cursor.getMessage()

createCursor​

def createCursor(options: SelectionOptions) -> TickCursor

Creates a cursor for reading data from this stream, according to the specified options, but initially with a fully restricted filter. The user must call TickCursor.reset at least once, in order to begin retrieving data. This method is equivalent to (but is slightly more optimal than) calling createCursor(options)

Arguments:

  • options SelectionOptions - Selection Options.

Returns:

A cursor used to read messages. Never null.

tryCursor​

@contextmanager
def tryCursor(options: SelectionOptions) -> TickCursor

contextmanager version of createCursor. Usage:

with stream.tryCursor(options) as cursor:
while cursor.next():
message = cursor.getMessage()

createLoader​

def createLoader(options: LoadingOptions) -> TickLoader

Creates a channel for loading data. The loader must be closed when the loading process is finished.

Arguments:

  • options LoadingOptions - Loading Options.

Returns:

  • TickLoader - created loader.

tryLoader​

@contextmanager
def tryLoader(options: LoadingOptions) -> TickLoader

Contextmanager version of createLoader. Usage:

with stream.tryLoader(options) as loader:
loader.send(message)

renameInstruments​

def renameInstruments(source: list[InstrumentIdentity],
target: list[InstrumentIdentity]) -> None

Renames list of instruments.

Arguments:

  • source list[InstrumentIdentity] - source entities list;

  • target list[InstrumentIdentity] - target entities list.

Example:

stream.renameInstruments([dxapi.InstrumentIdentity(dxapi.InstrumentType.EQUITY, 'GOOG'),
dxapi.InstrumentIdentity(dxapi.InstrumentType.EQUITY, 'IBM')],
[dxapi.InstrumentIdentity(dxapi.InstrumentType.EQUITY, 'GOOG_NEW'),
dxapi.InstrumentIdentity(dxapi.InstrumentType.FX, 'IBM_NEW')])

listSpaces​

def listSpaces() -> list[str]

Returns all created "spaces" for the stream. Default space returns as "" (empty string). If backing stream does not support spaces None will be returned.

renameSpace​

def renameSpace(newName: str, oldName: str) -> None

Rename existing space.

Arguments:

  • nameName str - space to rename.
  • oldName str - new space name.

deleteSpaces​

def deleteSpaces(spaces: list[str]) -> None

Removed given 'spaces' permanently.

Arguments:

  • spaces list[str] - list of spaces names to delete.

getTimeRange​

def getTimeRange(
entities: list[InstrumentIdentity] | list[str] | None = None
) -> list[int]

Return an inclusive range of times for which the specified entities have data in the database.

Arguments:

  • entities list[InstrumentIdentity] - A list of entities or list of symbols. If empty, return for all.

getSpaceTimeRange​

def getSpaceTimeRange(space: str) -> list[int]

An array consisting of two long timestamps (from and to) or None if no data was found.

Arguments:

  • space str - space name.

TickCursor​

class TickCursor(object)

A cursor (also known as iterator, or result set) for reading data from a stream. This class provides methods for dynamically reconfiguring the feed, as well as method reset for essentially re-opening the cursor on a completely different timestamp.

To get a cursor, use select method from TickDb or TickStream objects, or call executeQuery to open cursor to QQL result set.

Also cursor can be created with createCursor method, but it will be not initialized cursor, so cursor should be configured with types, entities and read time calling reset:

options = dxapi.SelectionOptions()
cursor = tickdb.createCursor(stream, options)
cursor.subscribeToAllEntities()
cursor.subscribeToAllTypes()
cursor.reset(timestamp)

next​

def next() -> bool

Moves cursor on to the next message. This method blocks until the next message becomes available, or until the cursor is determined to be at the end of the sequence. This method is illegal to call if isAtEnd() returns true.

Returns:

  • bool - false if at the end of the cursor.

getMessage​

def getMessage() -> InstrumentMessage

Returns an InstrumentMessage object cursor points at.

isAtEnd​

def isAtEnd() -> bool

Returns true if the last call to next() returned false. Returns false if next() has not been called yet. This method is legal to call any number of times at any point in the cursor's lifecycle.

nextIfAvailable​

def nextIfAvailable() -> int

Moves cursor on to the next message, but this method NOT blocks until the next message becomes available.

Returns:

  • NextResult - OK (0) if new message is available, END_OF_CURSOR (1) if cursor was closed, otherwise, UNAVAILABLE (2)

isClosed​

def isClosed() -> bool

Returns true, if cursor was closed

close​

def close() -> None

Close the cursor

getCurrentStreamKey​

def getCurrentStreamKey() -> str

Return the key of the stream that is the source of the current message.

reset​

def reset(
timestamp: int,
entities: list[InstrumentIdentity] | list[str] | None = None) -> None

Reposition the message source to a new point in time, while preserving current subscription.

Arguments:

  • timestamp int - The new position in time in millis.
  • entities 'list[InstrumentIdentity]' - list of entities to reset

subscribeToAllEntities​

def subscribeToAllEntities() -> None

Subscribe to all available entities.

clearAllEntities​

def clearAllEntities() -> None

Switch to selective subscription mode (if necessary) and clear the list.

addEntity​

def addEntity(entity: InstrumentIdentity) -> None

Add the specified entity to subscription.

Special note about options: The following fragment will subscribe to specific option contract "DAV 100417P00085000": cursor.addEntity(dxapi.InstrumentIdentity(dxapi.InstrumentType.OPTION, 'DAV 100417P00085000'));

While the following will subscribe to option root (and you will get all instruments with this root): cursor.addEntity(dxapi.InstrumentIdentity(dxapi.InstrumentType.OPTION, "DAV "));

addSymbol​

def addSymbol(symbol: str) -> None

Add the specified symbol to subscription.

addEntities​

def addEntities(entities: list[InstrumentIdentity]) -> None

Bulk add the specified entities to subscription.

addSymbols​

def addSymbols(symbols: list[str]) -> None

Bulk add the specified symbols to subscription.

removeEntities​

def removeEntities(entities: list[InstrumentIdentity]) -> None

Remove the specified entities from subscription.

removeSymbols​

def removeSymbols(symbols: list[str]) -> None

Remove the specified symbols from subscription.

removeEntity​

def removeEntity(entity: InstrumentIdentity) -> None

Remove the specified entity from subscription.

removeSymbol​

def removeSymbol(symbol: str) -> None

Remove the specified symbol from subscription.

subscribeToAllTypes​

def subscribeToAllTypes() -> None

Subscribe to all available types (no filtering).

addTypes​

def addTypes(types: list[str]) -> None

Add the specified type names to subscription.

removeTypes​

def removeTypes(types: list[str]) -> None

Remove the specified types from subscription.

setTypes​

def setTypes(types: list[str]) -> None

Subscribe to specified types.

add​

def add(types: list[str],
entities: list[InstrumentIdentity] | list[str]) -> None

Add the specified entities and types to subscription.

Arguments:

  • types list[str] - not-null array of type names to subscribe.
  • entities list[InstrumentIdentity] - not-null array of instruments to subscribe.

remove​

def remove(types: list[str],
entities: list[InstrumentIdentity] | list[str]) -> None

Remove the specified entities and types from subscription.

Arguments:

  • types list[str] - not-null array of type names to unsubscribe.
  • entities list[InstrumentIdentity] - not-null array of instruments to unsubscribe.

addStreams​

def addStreams(streams: list[TickStream]) -> None

Add streams to subscription. Current time and filter is used to query data from new sources.

Arguments:

  • streams 'list[TickStream]' - Streams to add.

removeStreams​

def removeStreams(streams: list[TickStream]) -> None

Remove streams from subscription.

Arguments:

  • streams list[TickStream] - Streams to remove.

removeAllStreams​

def removeAllStreams() -> None

Remove all streams from subscription.

setTimeForNewSubscriptions​

def setTimeForNewSubscriptions(timestamp: int) -> None

This method affects subsequent "add subscription" methods, such as, for instance, addEntity(). New subscriptions start at the specified time.

Arguments:

  • timestamp int - The time to use.

TickLoader​

class TickLoader(object)

Object which consumes messages.

Create loader from TickDb: options = dxapi.LoadingOptions() stream = tickdb.createLoader(stream, options)

Create loader from TickStream: options = dxapi.LoadingOptions() stream = stream.createLoader(options)

send​

def send(message: InstrumentMessage) -> None

This method is invoked to send a message to the object.

Arguments:

  • message InstrumentMessage - A temporary buffer with the message. By convention, the message is only valid for the duration of this call.

    A CompactMessage (returned by a cursor opened with SelectionOptions.compactMessages = True) can be sent as well: its fields are read from the slots and matched with the fields of the stream schema, also those whose names were converted to Python identifiers ('E.exchangeId' -> 'E_exchangeId').

flush​

def flush() -> None

Flushes all buffered messages by sending them to server. Note that calling 'send' method not guaranty that all messages will be delivered and stored to server.

isClosed​

def isClosed() -> bool

Returns true, if cursor was closed

close​

def close() -> None

Flushes and closes the loader

addListener​

def addListener(listener: ErrorListener) -> None

Register error listener. All writing data errors will be delivered to the listener. Note, that instance of listener should be stored in variable and sholdn't be destroyed until you close the loader.

Arguments:

  • listener ErrorListener - error listener to register.

removeListener​

def removeListener(listener: ErrorListener) -> None

Unsubscribe registered error listener.

Arguments:

  • listener ErrorListener - error listener to unsubscribe.

nErrorListeners​

def nErrorListeners() -> int

Returns number of registered error listeners

registerType​

def registerType(type: str) -> int

Register type of sending message to get type id. For performance reasons, you could specify type id instead of type name, for example:

message = dxapi.InstrumentMessage()
message.typeId = loader.registerType("deltix.timebase.api.messages.universal.PackageHeader")
// as alternative, you could write:
// message.typeName = "deltix.timebase.api.messages.universal.PackageHeader"
loader.send(message)

Arguments:

  • type str - name of type to register.

Returns:

  • int - id of registered type.

registerInstrument​

def registerInstrument(type: InstrumentType, symbol: str) -> int

Register instrument of sending message to get instrument id. For performance reasons, you could specify instrument id instead of symbol and instrument type, for example:

message = dxapi.InstrumentMessage()
message.instrumentId = loader.registerInstrument(dxapi.InstrumentType.EQUITY, 'AAPL')
// as alternative, you could write:
// message.instrumentType = 'EQUITY'
// message.symbol = 'AAPL'
loader.send(message)

Arguments:

  • type InstrumentType - type of instrument.

  • symbol str - instrument ticker.

Returns:

  • int - id of registered instrument.

registerInstrumentIdentity​

def registerInstrumentIdentity(instrument: InstrumentIdentity) -> int

Register instrument of sending message to get instrument id. For performance reasons, you could specify instrument id instead of symbol and instrument type, for example:

message = dxapi.InstrumentMessage()
message.instrumentId = loader.registerInstrumentIdentity(dxapi.InstrumentIdentity(dxapi.InstrumentType.EQUITY, 'AAPL'))
// as alternative, you could write:
// message.instrumentType = 'EQUITY'
// message.symbol = 'AAPL'
loader.send(message)

Arguments:

  • type InstrumentType - type of instrument.

  • symbol str - instrument ticker.

Returns:

  • int - id of registered instrument.

ErrorListener​

class ErrorListener(object)

Listener for errors related to loading/sending data into a TickLoader.

Usage:

class MyErrorListener(dxapi.ErrorListener):
def onError(self, errorClass, errorMsg):
print('Error: ' + errorMsg)

listener = MyErrorListener() # save listener
loader.addListener(listener)
loader.send()
...

loader.removeListener(listener)
loader.close()

SchemaDef​

class SchemaDef()

TimeBase stream schema definition class.

Example:

schema = stream.metadata()
tradeType = schema.findType('TradeMessage')

Properties:

  • all list[TypeDef] - all types of stream schema (including content, non-content classes and enums).

  • types list[TypeDef] - content (top level) types of stream.

TypeDef​

class TypeDef()

TimeBase stream type definition class.

Example:

schema = stream.metadata()
tradeType = schema.findType('TradeMessage')

Properties:

  • name str - name of type.

  • title str - title of type.

  • fields list[FieldDef] - list of type fields.

  • isEnum bool - true, if type is enum.

  • parent str - name of parent type.

  • isAbstract bool - true, if type if abstract.

FieldDef​

class FieldDef()

TimeBase type field definition class.

Example:

schema = stream.metadata()
tradeType = schema.findType('TradeMessage')
priceField = tradeType.findField('price')

Properties:

  • name str - name of field.

  • title str - title of field.

  • description str - description of field.

  • type DataTypeDef - type of field.

  • static bool - true, if field is static.

  • value str - static value of field.

  • relativeTo str - field name (used to specify that field decoding depends on another field value).

  • primaryKey bool - true, if field is a part of the message's primary key.

  • hide bool - true, if field is hidden.

DataTypeDef​

class DataTypeDef()

TimeBase field type definition class.

Example:

schema = stream.metadata()
tradeType = schema.findType('TradeMessage')
priceField = tradeType.findField('price')
priceField.type.encoding = 'IEEE64'

Properties:

  • name str - name of field type.

  • encoding str - encoding of field type.

  • nullable bool - true for nullable field types.

  • types list[str] - list of schema type names for polymorphic types (for objects).

  • elementType str - type name of array element data type (for arrays).

MultiplexerFeed​

class MultiplexerFeed()

__init__​

def __init__(streams: list[TickStream] | None = None,
timestamp: int = None,
types: list[str] | None = None,
entities: list[InstrumentIdentity] | list[str] | None = None,
qql: str = None,
qql_params: list[QueryParameter] | None = None)

Initialize a MultiplexerFeed.

Properties: timestamp (int): The start timestamp in millis.

streams (list[TickStream]): Streams from which data will be selected.

types (list[str]): Specified message types to be subscribed. If null, then all types will be subscribed.

entities (list[InstrumentIdentity | str]): Specified entities to be subscribed. If null, then all entities will be subscribed.

qql: Query string

qql_params (list[QueryParameter]): The parameter values of the query.

to_dict​

def to_dict()

Convert the MultiplexerFeed to a dictionary.

MultiplexerSubscription​

class MultiplexerSubscription()

__init__​

def __init__()

Initialize the subscription with an empty list of feeds.

subscribe_stream​

def subscribe_stream(stream: TickStream,
timestamp: int = None,
types: list[str] | None = None,
entities: list[InstrumentIdentity | str] | None = None)

Create a new feed using specified criteria and add it to the subscription.

Properties: timestamp (int): The start timestamp in millis.

stream (TickStream): Stream from which data will be selected.

types (list[str]): Specified message types to be subscribed. If null, then all types will be subscribed.

entities (list[InstrumentIdentity] | list[str]): Specified entities to be subscribed. If null, then all entities will be subscribed.

subscribe_streams​

def subscribe_streams(streams: list[TickStream],
timestamp: int = None,
types: list[str] | None = None,
entities: list[InstrumentIdentity | str] | None = None)

Create a new feed using specified criteria and add it to the subscription.

Properties: timestamp (int): The start timestamp in millis.

streams (list[TickStream]): Streams from which data will be selected.

types (list[str]): Specified message types to be subscribed. If null, then all types will be subscribed.

entities (list[InstrumentIdentity] | list[str]): Specified entities to be subscribed. If null, then all entities will be subscribed.

subscribe_qql​

def subscribe_qql(qql: str,
timestamp: int = None,
qql_params: list[QueryParameter] | None = None)

Create a new feed using a query (qql) and add it to the subscription.

Properties: qql: Query string

timestamp: The start timestamp in millis.

add_feed​

def add_feed(feed: MultiplexerFeed)

Add a feed to the subscription.

add_feeds​

def add_feeds(feeds: list[MultiplexerFeed] = [])

Add feeds to the subscription.

Properties: feeds: List of MultiplexerFeed objects to add.

to_dict​

def to_dict()

Convert the subscription to a dictionary.